package testClasses.xstream;

import utilities.Key;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

import eventManager.EventManager;

public class FakeControllerConverter implements Converter {

	private EventManager eventManager;
	
	public FakeControllerConverter(){}
	
	public FakeControllerConverter(EventManager eventManager) {
		this.eventManager = eventManager;
	}
	
	public boolean canConvert(Class clazz) {
		return clazz.equals(FakeController.class);
	}

	public void marshal(Object obj, HierarchicalStreamWriter writer,
			MarshallingContext context) {

		System.out.println("Marshalling FakeController");
		
		FakeController controller = (FakeController) obj;
		Key key = controller.getKey();
		writer.startNode("key");
		writer.setValue(key.getValue()+"");
		writer.endNode();
		
		writer.startNode("testDatum");
		writer.setValue(controller.getTestDatum()+"");
		writer.endNode();
		
	}

	public Object unmarshal(HierarchicalStreamReader reader,
			UnmarshallingContext context) {

		System.out.println("UNMarshalling FakeController");
		
		FakeController controller = new FakeController(eventManager);
		reader.moveDown();//traverse to Key node
		
		controller.setKey(new Key(Integer.parseInt(reader.getValue())));
		
		reader.moveUp();//move back to base node
		reader.moveDown();//down to next node, testDatum
		
		String testDatum = reader.getValue();//(String)context.convertAnother(controller, String.class);
		controller.setTestDatum(Integer.parseInt(testDatum));
		
		return controller;
		
	}

}
